// vue方法
import { router,addRoutes } from "~/router"

// api
import { getMenusList } from '~/api/system/menu'

// 公共方法
import { getToken } from '~/composables/auth'
import store from "./store"
import { toast, showFullLoading, hideFullLoading } from '~/composables/util'

// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
    // 显示loading
    showFullLoading()

    const token = getToken()
    //  没有登录，强制跳转登录页
    if (!token && to.path != "/login" && to.path != "/register") {
        toast("请先登录！", "error")

        return next({
            path: "/login"
        })
    }
    if (token && to.path == "/login") {
        toast("无需重复登录！", "error")
        return next({
            path: from.path
        })
    }

    // 已登录
    let hasNewRoutes = false
    if (token && !hasGetInfo) {
        let { menus,is_newuser,is_auth} = await store.dispatch("getUserInfo")
        hasGetInfo = true
        // 动态添加路由
        hasNewRoutes = addRoutes(menus)
    }



    // 设置页面的标题
    let titel = (to.meta.title ? to.meta.title : '') + "-融媒体分发"
    document.title = titel

    // 如果未认证，跳转个人中心页面
    if(store.state.user.is_auth != 1 && to.path!= "/user/user_home" && to.path!= "/login" && to.path!= "/auth" && to.path!= "/auth_company" && to.path!= "/agreement"){

        return next({
            path: "/user/user_home"
        })
    }else{
        hasNewRoutes ? next(to.path) : next()
    }

})


// 全局后置守卫
router.afterEach((to, from) => {
    hideFullLoading()
})